#!/bin/bash
# 部署脚本 - hydromodel_llm 服务

set -e  # 遇到错误立即退出

echo "========================================"
echo "部署 hydromodel_llm 服务"
echo "========================================"

# 配置信息
CONTAINER_NAME="hydromodel_llm"
IMAGE_NAME="hydromodel_llm:latest"
PORT=8084

# 数据库配置（从环境变量读取）
WATER_DATABASE_URL="${WATER_DATABASE_URL:-postgresql://postgres:water@10.48.0.85:5432/flood_data_augmentation}"
OLLAMA_BASE_URL="${OLLAMA_BASE_URL:-http://10.48.0.81:11434}"
OLLAMA_CHAT_MODEL="${OLLAMA_CHAT_MODEL:-qwen3:4b-instruct}"

# 检查 .env 文件
if [ -f ".env" ]; then
    echo ""
    echo "✅ 发现 .env 文件，将使用其中的配置"
    # 安全地加载环境变量（忽略注释和空行）
    set -a
    source <(grep -v '^#' .env | grep -v '^$' | sed 's/\r$//')
    set +a
else
    echo ""
    echo "⚠️  未找到 .env 文件，使用默认配置"
    echo "   如需自定义配置，请创建 .env 文件"
fi

# 停止并删除旧容器
echo ""
echo "1. 清理旧容器..."
if docker ps -a | grep -q $CONTAINER_NAME; then
    docker stop $CONTAINER_NAME 2>/dev/null || true
    docker rm $CONTAINER_NAME 2>/dev/null || true
    echo "   ✅ 旧容器已删除"
else
    echo "   ℹ️  没有旧容器需要清理"
fi

# 构建镜像
echo ""
echo "2. 构建镜像..."
docker build -t $IMAGE_NAME .
echo "   ✅ 镜像构建完成"

# 检查 SSL 证书
echo ""
echo "3. 检查 SSL 证书..."
SSL_CERT_PATH="/etc/letsencrypt/live/ws.waterism.tech/fullchain.pem"
USE_SSL="false"

if [ -f "$SSL_CERT_PATH" ]; then
    echo "   ✅ SSL 证书存在，将启用 HTTPS 模式"
    USE_SSL="true"
else
    echo "   ⚠️  SSL 证书不存在，将使用 HTTP 模式"
    echo "   证书路径: $SSL_CERT_PATH"
fi

# 启动新容器
echo ""
echo "4. 启动新容器..."

if [ "$USE_SSL" = "true" ]; then
    # HTTPS 模式
    docker run --name $CONTAINER_NAME -d \
      --restart=unless-stopped \
      -p $PORT:$PORT \
      -v $(pwd)/storage:/app/storage \
      -v /etc/letsencrypt:/etc/letsencrypt:ro \
      -e WATER_DATABASE_URL="$WATER_DATABASE_URL" \
      -e OLLAMA_BASE_URL="$OLLAMA_BASE_URL" \
      -e OLLAMA_CHAT_MODEL="$OLLAMA_CHAT_MODEL" \
      -e LLM_SERVICE_PORT="$PORT" \
      -e LLM_TEMPERATURE="0.3" \
      -e LLM_MAX_TOKENS="800" \
      -e USE_SSL="true" \
      -e SSL_CERTFILE="/etc/letsencrypt/live/ws.waterism.tech/fullchain.pem" \
      -e SSL_KEYFILE="/etc/letsencrypt/live/ws.waterism.tech/privkey.pem" \
      $IMAGE_NAME
    echo "   ✅ 容器已启动（HTTPS 模式）"
else
    # HTTP 模式
    docker run --name $CONTAINER_NAME -d \
      --restart=unless-stopped \
      -p $PORT:$PORT \
      -v $(pwd)/storage:/app/storage \
      -e WATER_DATABASE_URL="$WATER_DATABASE_URL" \
      -e OLLAMA_BASE_URL="$OLLAMA_BASE_URL" \
      -e OLLAMA_CHAT_MODEL="$OLLAMA_CHAT_MODEL" \
      -e LLM_SERVICE_PORT="$PORT" \
      -e LLM_TEMPERATURE="0.3" \
      -e LLM_MAX_TOKENS="800" \
      -e USE_SSL="false" \
      $IMAGE_NAME
    echo "   ✅ 容器已启动（HTTP 模式）"
fi

# 等待服务启动
echo ""
echo "5. 等待服务启动..."
sleep 5

# 检查容器状态
if docker ps | grep -q $CONTAINER_NAME; then
    echo "   ✅ 容器运行正常"
else
    echo "   ❌ 容器启动失败"
    echo ""
    echo "查看日志："
    docker logs $CONTAINER_NAME
    exit 1
fi

# 显示日志
echo ""
echo "6. 服务日志（最近20行）："
echo "----------------------------------------"
docker logs --tail 20 $CONTAINER_NAME

# 测试服务
echo ""
echo "7. 测试服务..."
sleep 3

if [ "$USE_SSL" = "true" ]; then
    # 测试 HTTPS
    if curl -k -s https://127.0.0.1:$PORT/api/llm/health > /dev/null 2>&1; then
        echo "   ✅ HTTPS 服务正常"
        echo ""
        echo "   测试响应："
        curl -k -s https://127.0.0.1:$PORT/api/llm/health | python -m json.tool 2>/dev/null || echo "   (JSON 格式化失败)"
    else
        echo "   ⚠️  HTTPS 服务可能未就绪，请稍后测试"
    fi
else
    # 测试 HTTP
    if curl -s http://127.0.0.1:$PORT/api/llm/health > /dev/null 2>&1; then
        echo "   ✅ HTTP 服务正常"
        echo ""
        echo "   测试响应："
        curl -s http://127.0.0.1:$PORT/api/llm/health | python -m json.tool 2>/dev/null || echo "   (JSON 格式化失败)"
    else
        echo "   ⚠️  HTTP 服务可能未就绪，请稍后测试"
    fi
fi

# 完成
echo ""
echo "========================================"
echo "✅ 部署完成！"
echo "========================================"
echo ""
echo "服务信息："
echo "  - 容器名称: $CONTAINER_NAME"
echo "  - 端口: $PORT"
if [ "$USE_SSL" = "true" ]; then
    echo "  - 模式: HTTPS (SSL 已启用)"
    echo "  - API 文档: https://ws.waterism.tech:$PORT/docs"
    echo "  - 本地访问: https://127.0.0.1:$PORT/docs"
else
    echo "  - 模式: HTTP"
    echo "  - API 文档: http://localhost:$PORT/docs"
fi
echo "  - 数据库: $WATER_DATABASE_URL"
echo "  - Ollama: $OLLAMA_BASE_URL"
echo "  - 模型: $OLLAMA_CHAT_MODEL"
echo ""
echo "常用命令："
echo "  查看日志: docker logs -f $CONTAINER_NAME"
echo "  停止服务: docker stop $CONTAINER_NAME"
echo "  重启服务: docker restart $CONTAINER_NAME"
echo "  进入容器: docker exec -it $CONTAINER_NAME bash"
echo ""
echo "测试命令："
if [ "$USE_SSL" = "true" ]; then
    echo "  curl -k https://127.0.0.1:$PORT/"
    echo "  curl -k https://127.0.0.1:$PORT/api/llm/health"
    echo "  curl -k https://ws.waterism.tech:$PORT/api/llm/health"
    echo ""
    echo "完整测试："
    echo '  curl -k -X POST "https://ws.waterism.tech:'"$PORT"'/api/llm/session/load" \\'
    echo '    -H "Content-Type: application/json" \\'
    echo '    -d '"'"'{"session_id": "your-session-id"}'"'"
else
    echo "  curl http://localhost:$PORT/"
    echo "  curl http://localhost:$PORT/api/llm/health"
    echo ""
    echo "完整测试："
    echo '  curl -X POST "http://localhost:'"$PORT"'/api/llm/session/load" \\'
    echo '    -H "Content-Type: application/json" \\'
    echo '    -d '"'"'{"session_id": "your-session-id"}'"'"
fi
echo ""

